//
//  ComposeViewController.swift
//  Mircoblog-swift
//
//  Created by zz on 16/3/3.
//  Copyright © 2016年 zz. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        

    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        textView.resignFirstResponder()
    }
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK: - 通知方法
    @objc private func keyboardWillChangeFrame(userInfo: NSNotification){
    
        
        // 1. 从字典中获取目标键盘位置
        // `CG的结构体` CGPoint/CGSize/CGRect 要保存在字典中，需要转换成 NSValue
        let rect = (userInfo.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 动画时长
        let duration = (userInfo.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        // 2. 更新 toolbar 的位置
        let offset = view.bounds.height - rect.origin.y
        tool.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-offset)
        }
        
        // 3. 动画显示约束变化
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //MARK: - 监听方法
    @objc private func cancel(){
    
        dismissViewControllerAnimated(true, completion: nil)
        print("\(__FUNCTION__)")
    }
    @objc private func postClick(){
    
        print("\(__FUNCTION__)")
    }
    @objc private func selectPicture(){
    
        print("\(__FUNCTION__)")
    }
    @objc private func selectEention(){
        
        print("\(__FUNCTION__)")
    }
    @objc private func selectTrend(){
        
        print("\(__FUNCTION__)")
    }
    @objc private func selectEmotion(){
        
        print("\(__FUNCTION__)")
    }
    @objc private func selectAdd(){
        
        print("\(__FUNCTION__)")
    }
    
    
    //MARK: - 私有控件
    private lazy var tool: UIToolbar = UIToolbar()
    private lazy var textView: ComposeTextView = ComposeTextView()
    


}
extension ComposeViewController:UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
//MARK: - 设置界面
extension ComposeViewController{

    private func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        
        // 1. 准备导航栏
        prepareNavigationBar()
    
        // 2. 准备工具栏
        prepareToolbar()
        
        // 3. 准备textView
        prepareTextView()
        

    }
    /// textView
    private func prepareTextView(){
    
        //添加
        view.addSubview(textView)
        
        textView.delegate = self
        
        //自动布局
        textView.snp_makeConstraints { (make) in
            make.left.equalTo(view)
            make.right.equalTo(view)
           // snp_topLayoutGuideBottom 如果上方有导航栏／状态栏..能够让开(不计算在内)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.bottom.equalTo(tool.snp_top)

        }
        
        //手动设置(测试文本视图)
//        textView.text = ""
//        textView.font = UIFont.systemFontOfSize(14)
//        textView.placeholder = "白痴c"
        
        
    }
    /// 工具栏
    private func prepareToolbar(){
    
     //1.添加tool
        view.addSubview(tool)

        //自动布局
        tool.snp_makeConstraints { (make) in
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
            make.size.equalTo(44)
        }
        
      //2.添加子控件
        let itemSettings = [["imageName": "compose_toolbar_picture",      "actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectEention"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectTrend"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmotion"],
                            ["imageName": "compose_add_background","actionName": "selectAdd"]]
        tool.items = [UIBarButtonItem]()
        for dict in itemSettings {
            let imageName = dict["imageName"]
            let item: UIButton = UIButton(zd_title: nil, imageName: imageName)
            if let actionName = dict["actionName"]{
                // 提示：如果用常量创建，需要使用 Selector(actionName) 构造函数
                item.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
//            tool.items?.append((item as! UIBarButtonItem)) 错误
            tool.items?.append(UIBarButtonItem(customView: item))
            tool.items?.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        tool.items?.removeLast()

    }
    /// 导航栏
    private func prepareNavigationBar(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "取消",
            style: .Plain,
            target: self,
            action: "cancel")
        
        let postButton: UIButton = UIButton(
            zd_title: "发布",
            fontSize: 14,
            color: UIColor.whiteColor(),
            backImageName: "common_button_orange")
        postButton.addTarget(self, action: "postClick", forControlEvents: .TouchUpInside)
        //大小
        postButton.frame = CGRect(x: 0, y: 0, width: 50, height: 35)
        //禁用设置
        postButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        postButton.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: postButton)
        //
        navigationItem.rightBarButtonItem?.enabled = false

        
        //设置导航标题
        let label: UILabel = UILabel()
        
          //1.设置文本属性
        let attrText: NSMutableAttributedString = NSMutableAttributedString(string: "发微博\n", attributes: [NSFontAttributeName:UIFont.systemFontOfSize(15),NSForegroundColorAttributeName:UIColor.darkGrayColor()])
        let userName: String = "user"
        let nameText: NSAttributedString = NSAttributedString(string: userName, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:UIColor.lightGrayColor()])
        attrText.appendAttributedString(nameText)
        
          //2.添加文本属性
        label.attributedText = attrText
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        
        navigationItem.titleView = label
        
        
    }
}
